<template>
	<view>
		<block v-if="!notifyData || !status">
			<uv-empty mode="search" v-if="devices.length === 0" text="无可用设备" :marginTop="160" :icon="empty">
				<uv-button type="primary" text="扫描蓝牙设备" @click="searchBle" style="width:600rpx;margin:75rpx;"></uv-button>
			</uv-empty>
			<view style="padding:25rpx;margin:25rpx;background:#fff;border-radius:25rpx;" v-else>
				<uv-list padding="25rpx">
					<uv-list-item
						v-for="(item, index) in devices"
						:key="index"
						:clickable="true"
						:show-extra-icon="true"
						:extra-icon="{ icon: 'order', size: '22' }"
						:title="item.name"
						@click="connectDevice(item)"
						show-arrow
					></uv-list-item>
				</uv-list>
			</view>
		</block>
		<block v-else>
			<device v-if="notifyData" :notify-data="notifyData" @readSetting="readSetting" @sendCommand="sendCommand"></device>
		</block>
		<!-- <view class="round-fixed-container" @click="disconnect" v-if="status || devices.length > 0">
			<view class="round-container">
				<text class="custom-icon custom-icon-lianjieduankai" style="font-size:48rpx;"></text>
			</view>
			<text class="font-small">断开连接</text>
		</view> -->
		<view style="margin:25rpx;" @click="disconnect" v-if="status || devices.length > 0">
			<uv-button type="error">断开连接</uv-button>
		</view>
	</view>
</template>
<script>
import { routeUrl, toast, modal, loading } from '@/util';
import { convert, crc32 } from '@/util/bluetooth';
import { command } from '@/util/formatter'
import device from '@/components/device';
export default {
	components: {
		device
	},
	data() {
		return {
			empty:'https://cdn.uviewui.com/uview/empty/search.png',
			status: false,
			devices: [],
			device: {
				name:'',
				deviceId: '', //已连接设备uuid
				services: '', //连接设备的服务
				characteristics: '', //连接设备的状KT
				serviceId: '', // 服务id,
				writeCharacteristicsId: '',
				notifyCharacteristicsId: ''
			},
			deviceNameAttr: ['doiot','KT'],
			ReadHOLD: 'FF0302650008',
			notifyData:'1'
			// notifyData: '10451045320FFF000100020000000000000000E0EE'
		};
	},
	onLoad() {
		uni.onBLEConnectionStateChange(res => {
			console.log(res);
			this.status = res.connected;
			if (!res.connected) {
				this.closeBluetoothAdapter();
			}
		});
	},
	watch:{
		device:{
			handler(newVal){
				if(newVal.deviceId){
					uni.setNavigationBarTitle({
						title:newVal.name
					})
				} else {
					uni.setNavigationBarTitle({
						title:'蓝牙调试工具'
					})
				}
			},
			deep:true,
			immediate:true
		}
	},
	methods: {
		readSetting(idx){
			console.log(idx)
		},
		disconnect(){
			modal('操作确认','确定要断开连接吗？',() => {
				if (this.device.deviceId) {
					uni.closeBLEConnection({
						deviceId: this.device.deviceId,
						success: res => {
							this.closeBluetoothAdapter();
						},
						fail(res) {
							console.log(res);
						}
					});
				} else {
					this.closeBluetoothAdapter();
				}
			})
		},
		initBle() {
			uni.openBluetoothAdapter({
				success: res => {
					//已打开
					uni.getBluetoothAdapterState({
						//蓝牙的匹配状态
						success: row => {
							// 开始搜索蓝牙设备
							uni.showLoading({
								title: '搜索中'
							});
							this.startBluetoothDeviceDiscovery();
						},
						fail(error) {
							toast('查看手机蓝牙是否打开');
						}
					});
				},
				fail: err => {
					toast('查看手机蓝牙是否打开');
				}
			});
		},
		// 开始搜索蓝牙设备
		startBluetoothDeviceDiscovery() {
			uni.startBluetoothDevicesDiscovery({
				success: res => {
					setTimeout(() => {
						//加个延迟、目的是为了设备搜索完毕再获取列表，不然获取为空列表
						// 获取设备列表
						this.onBluetoothDeviceFound();
						uni.hideLoading();
					}, 1000);
				},
				fail: err => {
					console.log(err);
				}
			});
		},
		// 获取设备列表
		onBluetoothDeviceFound() {
			uni.getBluetoothDevices({
				success: res => {
					this.devices = res.devices.filter(obj => {
						const name = obj.name;
						let deviceFindResults = [];
						this.deviceNameAttr.forEach(item => {
							if (name.indexOf(item) > -1) {
								deviceFindResults.push(obj);
							}
						});
					console.log(deviceFindResults)
						return deviceFindResults.length > 0;
					});
					if (this.devices.length === 0) {
						toast('未搜索到任何设备，请重试');
					}
				},
				fail: function() {
					toast('搜索蓝牙设备失败或附件暂无开启的蓝牙设备');
				},
				complete: function() {
					//设备获取完成之后  停止搜索
					uni.stopBluetoothDevicesDiscovery({
						success(res) {
							console.log('停止搜索蓝牙', res);
							uni.hideLoading()
						}
					});
				}
			});
		},
		searchBle() {
			if (this.device.deviceId) {
				uni.closeBLEConnection({
					deviceId: this.device.deviceId,
					success: res => {
						this.closeBluetoothAdapter('init');
					},
					fail(res) {
						console.log(res);
					}
				});
			} else {
				this.closeBluetoothAdapter('init');
			}
		},
		// 连接选中设备
		connectDevice(device) {
			this.device = device;

			loading('连接中');

			uni.createBLEConnection({
				deviceId: this.device.deviceId,
				success: res => {
					this.getBLEDeviceServices();
				},
				fail: res => {
					toast('连接失败，请重试');
				}
			});
		},
		// 获取服务uuid
		getBLEDeviceServices() {
			setTimeout(() => {
				uni.getBLEDeviceServices({
					deviceId: this.device.deviceId,
					success: res => {
						this.device.services = res.services;
						const validServices = res.services.filter(val => {
							return val.uuid.indexOf('0000FFF0') > -1;
						});
						if (validServices.length > 0) {
							this.device.serviceId = validServices[0].uuid;
							/* 获取连接设备的所有特征值 */
							this.getBLEDeviceCharacteristics();
						}
					},
					fail: res => {
						toast('获取服务失败');
					}
				});
			}, 2000);
		},
		// 获取特征值
		getBLEDeviceCharacteristics() {
			setTimeout(() => {
				uni.getBLEDeviceCharacteristics({
					deviceId: this.device.deviceId,
					serviceId: this.device.serviceId,
					success: res => {
						this.characteristics = res.characteristics;
						uni.hideLoading()
						for (var obj of res.characteristics) {
							let current_uuid = obj.uuid;
							if (current_uuid.indexOf('FFF1') !== -1) {
								this.device.writeCharacteristicsId = current_uuid;
							}
							if (current_uuid.indexOf('FFF2') > -1) {
								this.device.notifyCharacteristicsId = current_uuid;
								// this.getbleData();
							}
						}
					},
					fail: res => {
						toast('获取特征值失败');
					}
				});
			}, 1000);
		},
		getbleData() {
			const result = () => {
				uni.writeBLECharacteristicValue({
					//发送指令
					deviceId: this.device.deviceId,
					serviceId: this.device.serviceId,
					characteristicId: this.device.writeCharacteristicsId,
					value: convert(command(21,1)),
					success: (res) => {
						console.log(res)
						this.readData();
					},
					fail: (err) => {
						console.log(err)
					}
				});
			};
			result();
			// this.inter = setInterval(() => {
			// 	result();
			// }, 5000);
		},
		// 读取数据
		readData() {
			uni.onBLECharacteristicValueChange(res => {
				var value = buf2hex(res.value);
				this.notifyData = vale
			});
		},
		// 关闭蓝牙模块
		closeBluetoothAdapter(isInit = '') {
			uni.closeBluetoothAdapter({
				success: res => {
					clearInterval(this.inter);
					this.status = false;
					this.devices = [];
					this.services = [];
					this.device = {};
					this.deviceId = '';
				},
				fail: err => {
					clearInterval(this.inter);
					this.status = false;
					this.devices = [];
					this.services = [];
					this.device = {};
					this.deviceId = '';
				},
				complete: () => {
					if (isInit === 'init') {
						this.initBle();
					}
				}
			});
		},
		sendCommand(value){
			uni.writeBLECharacteristicValue({
				//发送指令
				deviceId: this.device.deviceId,
				serviceId: this.device.serviceId,
				characteristicId: this.device.writeCharacteristicsId,
				value: convert(value),
				success: (res) => {
					toast('操作成功 - ' + value)
				},
				fail: (err) => {
					console.log(err)
				}
			});
		}
	}
};
</script>
<style lang="scss">
page {
	background: #f0f0f0;
}
.round-fixed-container{
	position:fixed;
	bottom:192rpx;
	right:64rpx;
	width:120rpx;
	text-align:center;
	.round-container{
		width:120rpx;
		height:120rpx;
		border-radius:50%;
		line-height:120rpx;
		text-align:center;
		color:#fff;
		background:#3c9cff;
	}
	.font-small{
		font-size:24rpx;
	}
}
</style>
